package com.lmc.forum.exception;

import com.lmc.forum.common.AppResult;
import com.lmc.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
//    全局异常处理

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

//    处理自定义的已知异常
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult handleApplicationException(ApplicationException e) {
        e.printStackTrace();
        log.error("ApplicationException: {}", e.getMessage());
//        获取异常信息
        if(e.getErrResult() != null){
            return e.getErrResult();
        }
//        e.getMessage()获得的错误信息是Throwable中的错误信息，并不是自定义的错误信息
        return AppResult.failed(e.getMessage());
    }

//    处理全局未捕获的异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handleException(Exception e) {
        e.printStackTrace();
        log.error("Exception: {}", e.getMessage());
        if(e.getMessage() == null){
            return new AppResult().failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }

}
